package com.lmm.cg.zjgcg.pages.testtask;

/**
 * 测试Task
 */

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.lmm.cg.zjgcg.R;
import com.lmm.cg.zjgcg.config.ReqCodeConfig;
import com.lmm.cg.zjgcg.pages.rnplugins.UploadCallBack;
import com.lmm.cg.zjgcg.service.UploadAction;
import com.lmm.cg.zjgcg.task.BaseTask;
import com.lmm.cg.zjgcg.task.TaskCallBack;
import com.lmm.dresswisdom.lmmframe.retrofit.AppCallBack;
import com.lmm.dresswisdom.lmmframe.retrofit.AppClient;
import com.lmm.dresswisdom.lmmframe.util.FileUtils;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.ObservableEmitter;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


@Route(path = "/page/test")
public class TestTask extends AppCompatActivity implements View.OnClickListener {
    private final String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "cg" + File.separator;
    UploadAction uploadAction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_task);
        if (!new File(rootPath).exists()) {
            new File(rootPath).mkdirs();
        }
    }


    public void uploadJYXC(final File mfile, final UploadCallBack uploadCallBack) {
        uploadAction = AppClient.getRetrofit("http://221.224.118.58:5080/zjgszcg_2019/WtzfWebService/QWGLNew.asmx/").create(UploadAction.class);
        Map<String, String> params = new HashMap<>();
        params.put("FileStream", FileUtils.encodeBase64File(mfile));
        params.put("YeWuGuid", "8a808c7b6e4ddfc1016e4e1e94c70027");
        params.put("FileType", "image");
        params.put("PicType", "jpg");
        params.put("RefreshToken", "");
        params.put("AccessToken", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NzMyODIyODM4NTksInBheWxvYWQiOiJ7XCJpZFwiOlwiMS0xXCIsXCJ1c2VyTmFtZVwiOlwiYWRtaW5cIixcInRydWVOYW1lXCI6XCLns7vnu5_nrqHnkIblkZhcIixcInBob25lXCI6XCJcIixcImRlcHRJZFwiOlwiZDY4MDIzZTAtYWUyZi00N2YzLThlZDQtMjRmNzcyNWM5ZWU0XCIsXCJ0eXBlXCI6bnVsbCxcInN0YXRlXCI6MSxcInBhc3N3b3JkXCI6XCJcIixcInNleFwiOjAsXCJiaXJ0aERheVwiOm51bGwsXCJuYXRpb25cIjpcIlwiLFwicXV5dVwiOlwiXCIsXCJ6aGljaGVuZ1wiOlwiXCIsXCJob21lUGhvbmVcIjpcIlwiLFwiZU1haWxcIjpcIlwiLFwidXNlclB3ZFwiOlwiaUdrbE1UamlPOE10TnhQRHZrQ1Q2S0h1cmRScFNsVkZMRlpMRW9QTVRaVT1cIixcInNhbHRcIjpcImMrMml1a3lLZVM4MFdlYUIvQm5MZVE9PVwiLFwiZ3VhbmxpYW5xdXl1XCI6bnVsbCxcImluZGV4UGFnZVwiOlwiaW5kZXhcIixcImdseUZsYWdcIjoxLFwiYnVtZW5JZFwiOlwiXCIsXCJjYXF5XCI6MCxcImNhXCI6XCJcIixcInFxXCI6bnVsbH0ifQ.lXKGcLsdFxKf5tJFcpDLyEHHe_tKuzI4G2LYugzTDKc");
        AppClient.request(uploadAction.uploadJYCX((params)), new AppCallBack<HashMap<String, Object>>() {
            @Override
            public void onSuccess(HashMap<String, Object> result) {
                String imgId = result.get("image_id").toString();

                Log.i("Eric", imgId);
                ArrayList results = (ArrayList) result.get("results");
                if (results.size() > 0) {
                    HashMap<String, Object> car = (HashMap<String, Object>) results.get(0);
                    String number = car.get("license_plate_number").toString();
                    Log.i("Eric", number);
                    uploadCallBack.uploadFinish(number);
                } else {
                    uploadCallBack.uploadFail();
                }

            }

            @Override
            public void onFailure(String s) {
                uploadCallBack.uploadFail();
            }

            @Override
            public void onFinish() {

            }
        });
    }

    private static Map<String, RequestBody> generateRequestBody(Map<String, String> requestDataMap) {
        Map<String, RequestBody> requestBodyMap = new HashMap<>();
        for (String key : requestDataMap.keySet()) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),
                    requestDataMap.get(key) == null ? "" : requestDataMap.get(key));
            requestBodyMap.put(key, requestBody);
        }
        return requestBodyMap;
    }


    private void connectDevice() {
        new BaseTask<String>(new TaskCallBack<String>() {
            @Override
            public void onSuccess(String o) {
                Log.d("kaelpu", o);
            }

            @Override
            public void onFail(String s) {
                Log.d("kaelpu", s);
            }

            @Override
            public void onFinish() {
                Log.d("kaelpu", "onFinish");
            }
        }) {
            @Override
            public void exec(ObservableEmitter emitter) {
                getDrawableFromUrl();
                emitter.onNext("Hello world");
                emitter.onComplete();
            }
        }.run();
    }

    private Drawable getDrawableFromUrl() {
        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return getResources().getDrawable(R.drawable.ic_launcher_background);
    }


    @Override
    public void onClick(View view) {

    }

    public void uploadFileAction(View view) {

        choosePhoto();
//        uploadJYXC(null, new UploadCallBack() {
//            @Override
//            public void uploadFinish(String netaddress) {
//
//            }
//
//            @Override
//            public void uploadFail() {
//
//            }
//        });
    }

    public void choosePhoto() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, ReqCodeConfig.ReqCode_ChoosePhotoFromAlumb);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ReqCodeConfig.ReqCode_ChoosePhotoFromAlumb) {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                CompressImg(uri);
            }
        }
    }

    private void CompressImg(Uri loadUri) {
        Luban.with(this)
                .load(loadUri)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        LogUtils.write("start");
                    }

                    @Override
                    public void onSuccess(File file) {
                        String path = file.getPath();
                        LogUtils.write("FilePath:" + path);
                        uploadJYXC(file, new UploadCallBack() {
                            @Override
                            public void uploadFinish(String netaddress) {

                            }

                            @Override
                            public void uploadFail() {

                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.write(e.getMessage());
                    }
                }).launch();
    }


    private String getPath() {
        return rootPath;
    }

}
